package com.jdew.thkj.activity;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.TabLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jdew.thkj.R;
import com.jdew.thkj.adapter.JDMuAdapter;
import com.jdew.thkj.base.BaseActivity;
import com.jdew.thkj.bean.JDListBean;
import com.jdew.thkj.listener.AppBarStateChangeListener;
import com.jdew.thkj.manager.AppConfig;
import com.jdew.thkj.manager.WrapContentGridLayoutManager;
import com.jdew.thkj.network.RetrofitManager;
import com.jdew.thkj.network.api.RequestApi;
import com.jdew.thkj.onitemInterface.OnItemClickListener;
import com.jdew.thkj.utils.DeviceUtils;
import com.jdew.thkj.utils.MD5Utils;
import com.jdew.thkj.utils.RegexValidateUtils;
import com.jdew.thkj.utils.ToastUtils;
import com.jdew.thkj.utils.WeiboDialogUtils;
import com.jdew.thkj.view.Reflex;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by yangzai on 2018/8/8.
 */

public class JdActivity extends BaseActivity {
    @Bind(R.id.swipeRefreshLayout)
    SwipeRefreshLayout swipeRefreshLayout;
    @Bind(R.id.search)
    View search;
    @Bind(R.id.back)
    ImageView back;
    @Bind(R.id.title)
    TextView title;
    @Bind(R.id.tabLayout)
    TabLayout tabLayout;
    @Bind(R.id.swipe_target)
    RecyclerView recycleView;
    @Bind(R.id.appbar)
    AppBarLayout appbar;
    @Bind(R.id.price)
    RadioButton price;
    @Bind(R.id.main_tab)
    RadioGroup main_tab;
    @Bind(R.id.yj)
    RadioButton yj;
    @Bind(R.id.down)
    TextView down;
    @Bind(R.id.noresult)
    TextView noresult;
    @Bind(R.id.result_view)
    RelativeLayout resultView;
    @Bind(R.id.newst)
    RadioButton newst;
    @Bind(R.id.hot)
    RadioButton hot;
    private String[] mTilte;
    private JDMuAdapter adapter;
    private List<JDListBean.DataBean> list = new ArrayList<>();
    private int page = 1;
    private boolean isLoading = true;
    private String itemId;
    private String key = "9987";
    private Dialog mWeiboDialog;
    private Boolean paixun = false;
    private Boolean pricepaixun = false;
    private String sort = "0";
    private String sortby = "desc";

    @Override
    public int bindLayout() {
        return R.layout.activity_jd;
    }

    @Override
    public void initView(View view) {
        title.setText("京东");
        back.setVisibility(View.VISIBLE);
        back.setOnClickListener(this);
        search.setOnClickListener(this);
        down.setVisibility(View.GONE);
        sp = getSharedPreferences("user", Activity.MODE_PRIVATE);
        editor = sp.edit();
        xiding();
        RadioButton rb = (RadioButton) main_tab.getChildAt(0);
        rb.setChecked(true);
        Drawable drawable = getResources().getDrawable(R.mipmap.price_normal);
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
        mTilte = getResources().getStringArray(R.array.tab_jd_Title);
        for (int i = 0; i < mTilte.length; i++) {
            tabLayout.addTab(tabLayout.newTab().setText(mTilte[i]));
        }
        adapter = new JDMuAdapter(this, list);
        recycleView.setLayoutManager(new WrapContentGridLayoutManager(this, 2, GridLayoutManager.VERTICAL, false));
        recycleView.setAdapter(adapter);
        initRefresh();
        RequestData();
        Reflex.setTabWidth(tabLayout, 40);
        changeStatusBarTextColor();
        yj.setCompoundDrawables(null, null, drawable, null);
        newst.setOnClickListener(this);
        yj.setOnClickListener(this);
        hot.setOnClickListener(this);
        price.setOnClickListener(this);
        price.setCompoundDrawables(null, null, drawable, null);
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                page = 1;
                if (tab.getPosition() == 0) {
                    key = "9987";
                } else if (tab.getPosition() == 1) {
                    key = "652";
                } else if (tab.getPosition() == 2) {
                    key = "670";
                } else if (tab.getPosition() == 3) {
                    key = "1319";
                } else if (tab.getPosition() == 4) {
                    key = "11729";
                } else if (tab.getPosition() == 5) {
                    key = "12218";
                } else if (tab.getPosition() == 6) {
                    key = "6196";
                } else if (tab.getPosition() == 7) {
                    key = "12259";
                } else if (tab.getPosition() == 8) {
                    key = "737";
                } else if (tab.getPosition() == 9) {
                    key = "1620";
                } else if (tab.getPosition() == 10) {
                    key = "1315";
                } else if (tab.getPosition() == 11) {
                    key = "16750";
                } else if (tab.getPosition() == 12) {
                    key = "1318";
                } else if (tab.getPosition() == 13) {
                    key = "1320";
                } else if (tab.getPosition() == 14) {
                    key = "1672";
                } else if (tab.getPosition() == 15) {
                    key = "6144";
                } else if (tab.getPosition() == 16) {
                    key = "6233";
                }
                RequestData();
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        setRecycleView();
        adapter.setItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                if (!RegexValidateUtils.isFastClick()) {
                    return;
                }
                if (sp.getString("SpareTwo", "").equals("")) {
                    startActivity(new Intent(JdActivity.this, LoginActivity.class));
                } else if (sp.getString("UserSjPhone", "").equals("") && (!sp.getString("SpareTwo", "").equals("1"))) {
                    toset("检测到您还没有绑定上级,请到我的页面绑定上级");
                } else {
                    itemId = list.get(position).getSkuId();
                    toDetail();
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        Drawable drawable = getResources().getDrawable(R.mipmap.price_normal);
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
        switch (v.getId()) {
            case R.id.back: {
                finish();
            }
            break;
            case R.id.search: {
                Bundle b = new Bundle();
                b.putSerializable("source", "jd");
                startActivity(MainSearchActivity.class, b);
            }
            break;
            case R.id.newst: {
                Drawable drawable1 = getResources().getDrawable(R.mipmap.price_normal);
                drawable1.setBounds(0, 0, drawable1.getMinimumWidth(), drawable1.getMinimumHeight());
                sort = "0";
                price.setCompoundDrawables(null, null, drawable1, null);
                yj.setCompoundDrawables(null, null, drawable1, null);
                page = 1;
                RequestData();
            }
            break;
            case R.id.yj: {
                price.setCompoundDrawables(null, null, drawable, null);
                sort = "4";
                if (!paixun) {
                    Drawable drawable2 = getResources().getDrawable(R.mipmap.price_down);
                    drawable2.setBounds(0, 0, drawable2.getMinimumWidth(), drawable2.getMinimumHeight());
                    yj.setCompoundDrawables(null, null, drawable2, null);
                    sortby = "desc";
                    paixun = true;
                } else {
                    Drawable drawable3 = getResources().getDrawable(R.mipmap.price_up);
                    drawable3.setBounds(0, 0, drawable3.getMinimumWidth(), drawable3.getMinimumHeight());
                    yj.setCompoundDrawables(null, null, drawable3, null);
                    paixun = false;
                    sortby = "asc";
                }
                page = 1;
                RequestData();
            }
            break;
            case R.id.hot: {
                Drawable drawable4 = getResources().getDrawable(R.mipmap.price_normal);
                drawable4.setBounds(0, 0, drawable4.getMinimumWidth(), drawable4.getMinimumHeight());
                sortby="desc";
                sort = "2";
                price.setCompoundDrawables(null, null, drawable4, null);
                yj.setCompoundDrawables(null, null, drawable4, null);
                page = 1;
                RequestData();
            }
            break;
            case R.id.price: {
                yj.setCompoundDrawables(null, null, drawable, null);
                sort = "1";
                if (!pricepaixun) {
                    Drawable drawable5 = getResources().getDrawable(R.mipmap.price_down);
                    drawable5.setBounds(0, 0, drawable5.getMinimumWidth(), drawable5.getMinimumHeight());
                    price.setCompoundDrawables(null, null, drawable5, null);
                    sortby = "desc";
                    pricepaixun = true;
                } else {
                    Drawable drawable6 = getResources().getDrawable(R.mipmap.price_up);
                    drawable6.setBounds(0, 0, drawable6.getMinimumWidth(), drawable6.getMinimumHeight());
                    price.setCompoundDrawables(null, null, drawable6, null);
                    pricepaixun = false;
                    sortby = "asc";
                }
                page = 1;
                RequestData();
            }
            break;
            default:
                break;
        }
    }


    public void xiding() {
        appbar.addOnOffsetChangedListener(new AppBarStateChangeListener() {

            @Override
            public void onStateChanged(AppBarLayout appBarLayout, State state) {
                if (state == State.EXPANDED) {
                    //展开状态
                    swipeRefreshLayout.setEnabled(true);
                } else if (state == State.COLLAPSED) {
                    //折叠状态
                    swipeRefreshLayout.setEnabled(false);
                } else {//中间状态
                    swipeRefreshLayout.setEnabled(false);

                }
            }
        });
    }

    public void RequestData() {
        if (!DeviceUtils.isNetworkAvalible(this)) {
            if (!isFinishing()) {
                ToastUtils.getInstance(this).showMessage("网络连接错误请检查");
            }
            return;
        }
        String timesamp = RegexValidateUtils.getTime13();
        String numsamp = RegexValidateUtils.getRandom10();
        HashMap<String, Object> map = new HashMap();
        map.put("cid", key);
        map.put("pageIndex", page);
        map.put("sortby", sortby);
        map.put("sort", sort);
        if (null == mWeiboDialog || !mWeiboDialog.isShowing()) {
            mWeiboDialog = WeiboDialogUtils.createLoadingDialog(this);
        }
        RetrofitManager.getInstance(AppConfig.BASE_URL).createReq(RequestApi.class).Displaylist(map, RegexValidateUtils.getUniquePsuedoID(), timesamp, numsamp, MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp + numsamp + RegexValidateUtils.getUniquePsuedoID() + sp.getString("SignToken", "") + "cid" + key + "pageIndex" + page + "sortby" + sortby+"sort" + sort)).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<JDListBean>() {
            @Override
            public void onCompleted() {
                WeiboDialogUtils.closeDialog(mWeiboDialog);
            }

            @Override
            public void onError(Throwable e) {
                WeiboDialogUtils.closeDialog(mWeiboDialog);
            }

            @Override
            public void onNext(JDListBean bean) {
                WeiboDialogUtils.closeDialog(mWeiboDialog);
                if (bean.getCode().equals("0")) {
                    if (null == bean.getData() && list.size() == 0) {
                        resultView.setVisibility(View.VISIBLE);
                        noresult.setText("没有符合该条件的搜索!");
                        list.clear();
                        adapter.setDataList(list);
                        return;
                    }
                    resultView.setVisibility(View.GONE);
                    if (page == 1) {
                        list.clear();
                        adapter.setDataList(list);
                    }
                    list.addAll(bean.getData());
                    adapter.setDataList(list);
                    if (bean.getData().size() < 20) {
                        adapter.changeMoreStatus(adapter.NO_LOAD_MORE);
                    } else {
                        adapter.changeMoreStatus(adapter.LOADING_MORE);
                    }
                    isLoading = false;
                    swipeRefreshLayout.setRefreshing(false);
                }
            }
        });
    }

    private void initRefresh() {
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                page = 1;
                RequestData();
                swipeRefreshLayout.setRefreshing(false);
            }
        });
    }

    public void setRecycleView() {
        recycleView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
                LinearLayoutManager linearManager = null;
                if (layoutManager instanceof LinearLayoutManager) {
                    linearManager = (LinearLayoutManager) layoutManager;
                }
                int lastVisibleItemPosition = linearManager.findLastVisibleItemPosition();
                if (lastVisibleItemPosition + 1 == adapter.getItemCount()) {
                    boolean isRefreshing = swipeRefreshLayout.isRefreshing();
                    if (isRefreshing) {
                        adapter.notifyItemRemoved(adapter.getItemCount());
                        return;
                    }
                    if (!isLoading) {
                        isLoading = true;
                        page++;
                        RequestData();
                    }
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }
        });
    }

    private void changeStatusBarTextColor() {
        if (Build.VERSION.SDK_INT >= 21) {
            Window window = this.getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            getWindow().setStatusBarColor(getResources().getColor(R.color.color_ffffff));
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);//设置状态栏黑色字体
        }
    }

    public void toDetail() {
        Bundle b = new Bundle();
        b.putSerializable("itemId", itemId);
        startActivity(JDProductDetailActivity.class, b);
    }
}
